<?php
namespace App\Http\Controllers;
use App\Services\OSS;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Database\Eloquent\Model;
use App\Http\Controllers\Controller;
use App\tw_articles;
use App\tw_categories;
use App\tw_blocks;
use App\Services\SignatureHelper;
const JAVA_API_URI='114.215.173.236:8774';
// const TEST_JAVA_API_URI='121.199.71.116:8774';
const TEST_JAVA_API_URI='114.215.173.236:8774';
const ACTIVITYLIST='/stationActivity/list';
const ACTIVITYPUT='/stationActivity/release';
const ACTIVITYCLOSE='/stationActivity/closeActivity';
const ACTIVITYGET='/stationActivity/showActivityContent';
const ACTIVITYDATA='/stationActivity/showDetails';
const SKULIST='/exchange/service/list';
const SKUINFO='/exchange/service/info';
const SKUDEL='/exchange/service/delete';
const SKUPUT='/exchange/service/save';
const SKULOG='/exchange/record/list';
const USERLIST='/user/manage/list';
const USEREXPORT='/user/manage/export';
const USERPOINTUPDATE='/user/point/change';
const DOWNLIST='/data/manage/list';
const SECKILLLIST='/seckill/page';
const SECKILLADD='/seckill/add';
const SECKILLEDIT='/seckill/edit';
const DOWNADD='/data/add';
const DOWNTOP='/data/top';
const DOWNDELETE='/data/delete';
const DOWNENABLE='/data/enable';
const DOWNINFO='/data/view';
const DOWNEDIT='/data/edit';
const SECKILLDELETE='/seckill/delete';
const SECKILLINFO='/seckill/view';


class CmsService extends Controller
{
    use \App\Traits\ApiTrait, \App\Traits\SessionTrait, \App\Traits\AjaxTrait, \App\Traits\DbTrait, \App\Traits\UserTrait;
    public $curl;
    private $_requestData;
    public function __construct(Request $request)
    {
        $this->_requestData = $request->all();
        $this->curl = new \Ixudra\Curl\CurlService();
    }
    public static function toArray($obj){
      $obj=json_encode($obj);
      $obj=json_decode($obj,true);
      return $obj;
    }

    public function verifyLoginState($userId,$t){
      $time=time();
      $data=DB::table('tw_users')->whereRaw('userId = ? and t= ?',[$userId,$t])->first();
      // print_r($data);
      $data=$this->toArray($data);
      // print_r($data);
      if($data['userId']!=null && $data!=null){
        if($data['expireTime']<$time) return 3;
        return 1;
      }
      return 2;
    }

    public function verifyKeyState($appName,$accessKey){
      $time=time();
      $appName=strval($appName);
      $accessKey=strval($accessKey);
      $data=DB::table('tw_appKeys')->whereRaw('appName = ? and accessKey= ?',[$appName,$accessKey])->first();
      // var_dump($data);
      $data=$this->toArray($data);
      // print_r($data);
      if($data['appId']!=null && $data!=null){
        if($data['expireTime']<$time) return 3;
        return 1;
      }
      return 2;
    }

    public function formatDataBody($data,$status=200,$msg='',$code='0'){
        $resultData=[
          'code'=>$code,
          'status'=>$status,
          'msg'=>$msg,
          'data'=>$data,
        ];
        return json_encode($resultData);
    }

    /**
    *校验用户名和密码*/
    function verifyUserPw($userName,$password){
      if($userName!=''&&$password!=''&&$userName!=null&&$password!=null){
        // $password=MD5(MD5($password));
        $data=DB::table('tw_users')->whereRaw('userName = ? and password= ?',[$userName,$password])->first();
        if($data!=null){
          return [
            'code'=>200,
            'msg'=>'成功',
            'data'=>$this->toArray($data),
          ];
        }
        return [
          'code'=>0,
          'msg'=>'用户不存在或输入错误',
          'data'=>null,
        ];
      }
      return [
        'code'=>0,
        'msg'=>'用户名或密码为空',
        'data'=>null,
      ];
    }
    //登录服务方法
    public function login(Request $request){
      $userName=$request->userName;
      $password=$request->password;
      $verifyUserPw=$this->verifyUserPw($userName,$password);
      $data=$verifyUserPw['data'];
      unset($data['password']);
      //查库结果为非法时直接返回失败
      if($verifyUserPw['code']==0) return response($this->formatDataBody($data,'0',$verifyUserPw['msg']));
      //以下正式处理登录写库业务
      DB::beginTransaction();
      try {
        $t=MD5(time().$userName);
        $expire=3600*24+time();
        $bool= DB::table('tw_users')->where('userName', $userName)->update(['expireTime'=>$expire,'t'=>$t]);
        if($bool){
          $data['expireTime']=$expire;
          $data['t']=$t;
          DB::commit();
          return response($this->formatDataBody($data,'200',$verifyUserPw['msg']));
        }
      } catch (\Exception $e) {
          DB::rollback();
          return response($this->formatDataBody($data,'0','数据库写入错误'.'/\n'.$e));
      }
      //不明异常时抛出服务器错误
      DB::rollback();
      return response($this->formatDataBody($data,'0','登录失败，服务器错误'));
    }
    //登出
    public function logout(Request $request){
      $userId=$request->userId;
      $t=MD5(time().$userId);
      DB::beginTransaction();
      try {
        $bool= DB::table('tw_users')->where('userId', $userId)->update(['t'=>$t]);
        if($bool){
          DB::commit();
          return response($this->formatDataBody(null,'200','操作成功'));
        }
        else{
          DB::rollback();
          return response($this->formatDataBody(null,'0','操作失败，不存在的用户'));
        }
      } catch (\Exception $e) {
        DB::rollback();
        return response($this->formatDataBody(null,'0','操作失败，不存在的用户'));
      }
      //不明异常时抛出服务器错误
      DB::rollback();
      return response($this->formatDataBody(null,'0','失败，服务器错误'));
    }

    //发布文章,除活动外
    public function addArticle(Request $request){
      $userId=$request->userId;
      $t=$request->t;
      $insertData['articleTitle']=$request->articleTitle;
      $insertData['categoryId']=$request->categoryId;
      $insertData['clientType']=$request->clientType;
      $insertData['articleContract']=$request->articleContract;
      $insertData['articleContent']=$request->articleContent;
      $insertData['linkUrl']=$request->linkUrl;
      $insertData['articleType']=$request->articleType;
      $insertData['mainPic']=$request->mainPic;
      $insertData['videoUrl']=$request->videoUrl;
      $insertData['videoLenth']=$request->videoLenth;
      $insertData['sourceFrom']=$request->sourceFrom;
      $insertData['articleKeywords']=$request->articleKeywords;
      $insertData['articleDesc']=$request->articleDesc;
      $insertData['createAt']=time();
      $insertData['updateAt']=$insertData['createAt'];
      $verifyLoginState=$this->verifyLoginState($userId,$t);
      if($verifyLoginState==2 || $verifyLoginState==3) return response($this->formatDataBody(null,'-1','登录已失效'));
      DB::beginTransaction();
      try {
        $newId = tw_articles::insertGetId($insertData);
        DB::commit();
        return response($this->formatDataBody(['articleId'=>$newId],'200','操作成功'));
      } catch (\Exception $e) {
        DB::rollback();
        return response($this->formatDataBody(null,'0','失败，服务器错误'));
      }
      return response($this->formatDataBody(null,'0','失败，服务器错误'));
    }
    //创建栏目
    public function createCategory(Request $request){
      $userId=$request->userId;
      $t=$request->t;
      $verifyLoginState=$this->verifyLoginState($userId,$t);
      if($verifyLoginState==2 || $verifyLoginState==3) return response($this->formatDataBody(null,'-1','登录已失效'));
      $insertData['categoryName']=$request->categoryName;
      $insertData['mainPic']=$request->mainPic;
      $insertData['clientType']=$request->clientType;
      $insertData['markCode']=MD5(time());
      DB::beginTransaction();
      try {
        $newId = tw_categories::insertGetId($insertData);
        DB::commit();
        return response($this->formatDataBody(['categoryId'=>$newId],'200','操作成功'));
      } catch (\Exception $e) {
        DB::rollback();
        return response($this->formatDataBody(null,'0','失败，服务器错误'));
      }
      return response($this->formatDataBody(null,'0','失败，服务器错误'));
    }
    //创建布局元素
    public function createBlock(Request $request){
      $userId=$request->userId;
      $t=$request->t;
      $verifyLoginState=$this->verifyLoginState($userId,$t);
      if($verifyLoginState==2 || $verifyLoginState==3) return response($this->formatDataBody(null,'-1','登录已失效'));
      $insertData['blockName']=$request->blockName;
      $insertData['mainPic']=$request->mainPic;
      $insertData['isList']=$request->isList;
      $insertData['clientType']=$request->clientType;
      $insertData['markCode']=MD5(time());
      DB::beginTransaction();
      try {
        $newId = tw_blocks::insertGetId($insertData);
        DB::commit();
        return response($this->formatDataBody(['blockId'=>$newId],'200','操作成功'));
      } catch (\Exception $e) {
        DB::rollback();
        return response($this->formatDataBody(null,'0','失败，服务器错误'));
      }
      return response($this->formatDataBody(null,'0','失败，服务器错误'));
    }

    //布局元素回显
    public function getBlock(Request $request){
      $userId=$request->userId;
      $t=$request->t;
      $verifyLoginState=$this->verifyLoginState($userId,$t);
      if($verifyLoginState==2 || $verifyLoginState==3) return response($this->formatDataBody(null,'-1','登录已失效'));
      $blockId=$request->blockId;
      $data=DB::table('tw_blocks')->whereRaw('blockId = ?',[$blockId])->first();
      if($data!=null){
        $data->blockData=json_decode($data->blockData);
        return response($this->formatDataBody($data,'200','操作成功'));
      }
      return response($this->formatDataBody($data,'0','数据不存在'));
    }
    //栏目列表
    public function getCategoryList(Request $request){
      $userId=$request->userId;
      $t=$request->t;
      $verifyLoginState=$this->verifyLoginState($userId,$t);
      if($verifyLoginState==2 || $verifyLoginState==3) return response($this->formatDataBody(null,'-1','登录已失效'));
      $clientType=$request->clientType;
      $pageNum=$request->pageNum;
      $pageSize=$request->pageSize;
      if($pageSize==0)$pageSize=20;
      if($pageNum>0){
        $count=DB::table('tw_categories')->where(['clientType'=>$clientType,'isDel'=>'0'])->count();
        $DBData=DB::table('tw_categories')->whereRaw('clientType = ? and isDel = ? ',[$clientType,'0'])->orderby('categoryId','desc')->offset($pageNum*$pageSize-$pageSize)->limit($pageSize)->get();
        $result=[
          'count'=>$count,
          'list'=>$DBData,
        ];
          return response($this->formatDataBody($result));
      }
      $DBData=DB::table('tw_categories')->whereRaw('clientType = ? and isBan = ? and isDel = ? ',[$clientType,'0','0'])->orderby('categoryId','desc')->get();
      $result=[
        'count'=>0,
        'list'=>$DBData,
      ];
      return response($this->formatDataBody($result));
    }
    //版块信息
    public function getBlockList(Request $request){
      $userId=$request->userId;
      $t=$request->t;
      $verifyLoginState=$this->verifyLoginState($userId,$t);
      if($verifyLoginState==2 || $verifyLoginState==3) return response($this->formatDataBody(null,'-1','登录已失效'));
      $clientType=$request->clientType;
      $pageNum=$request->pageNum;
      $pageSize=$request->pageSize;
      if($pageSize==0)$pageSize=20;
      if($pageNum>0){
        $count=DB::table('tw_blocks')->where(['clientType'=>$clientType,'isDel'=>'0'])->count();
        $DBData=DB::table('tw_blocks')->whereRaw('clientType = ? and isDel = ? ',[$clientType,'0'])->orderby('blockId','desc')->offset($pageNum*$pageSize-$pageSize)->limit($pageSize)->get();
        $result=[
          'count'=>$count,
          'list'=>$DBData,
        ];
          return response($this->formatDataBody($result));
      }
      $DBData=DB::table('tw_blocks')->where(['clientType'=>$clientType,'isDel'=>'0'])->orderby('blockId','desc')->get();
      $result=[
        'count'=>0,
        'list'=>$DBData,
      ];
      return response($this->formatDataBody($result));
    }
    //配置元素
    public function updateBlock(Request $request){
      $userId=$request->userId;
      $t=$request->t;
      $verifyLoginState=$this->verifyLoginState($userId,$t);
      if($verifyLoginState==2 || $verifyLoginState==3) return response($this->formatDataBody(null,'-1','登录已失效'));
      $blockId=$request->blockId;
      // $blockData=json_encode($request->blockData);
      $blockData=$request->blockData;
      try {
        $bool= DB::table('tw_blocks')->where('blockId', $blockId)->update(['blockData'=>$blockData]);
        return response($this->formatDataBody(null,'200','操作成功'));
      } catch (\Exception $e) {
        return response($this->formatDataBody(null,'0','失败，服务器错误'));
      }
    }
    //栏目名称
    public function updateCategoryName(Request $request){
      $userId=$request->userId;
      $t=$request->t;
      $verifyLoginState=$this->verifyLoginState($userId,$t);
      if($verifyLoginState==2 || $verifyLoginState==3) return response($this->formatDataBody(null,'-1','登录已失效'));
      $categoryName=$request->categoryName;
      $categoryId=$request->categoryId;
      try {
        $bool= DB::table('tw_categories')->where('categoryId', $categoryId)->update(['categoryName'=>$categoryName]);
        return response($this->formatDataBody(null,'200','操作成功'));
      } catch (\Exception $e) {
        return response($this->formatDataBody(null,'0','失败，服务器错误'));
      }
    }
    //元素名称
    public function updateBlockName(Request $request){
      $userId=$request->userId;
      $t=$request->t;
      $verifyLoginState=$this->verifyLoginState($userId,$t);
      if($verifyLoginState==2 || $verifyLoginState==3) return response($this->formatDataBody(null,'-1','登录已失效'));
      $blockName=$request->blockName;
      $blockId=$request->blockId;
      try {
        $bool= DB::table('tw_blocks')->where('blockId', $blockId)->update(['blockName'=>$blockName]);
        return response($this->formatDataBody(null,'200','操作成功'));
      } catch (\Exception $e) {
        return response($this->formatDataBody(null,'0','失败，服务器错误'));
      }
    }
    //停用启用元素
    public function banBlock(Request $request){
      $userId=$request->userId;
      $t=$request->t;
      $verifyLoginState=$this->verifyLoginState($userId,$t);
      if($verifyLoginState==2 || $verifyLoginState==3) return response($this->formatDataBody(null,'-1','登录已失效'));
      $blockId=$request->blockId;
      $isBan=$request->isBan;
      try {
        $bool= DB::table('tw_blocks')->where('blockId', $blockId)->update(['isBan'=>$isBan]);
        return response($this->formatDataBody(null,'200','操作成功'));
      } catch (\Exception $e) {
        return response($this->formatDataBody(null,'0','失败，服务器错误'));
      }
    }
    //停用启用栏目
    public function banCategory(Request $request){
      $userId=$request->userId;
      $t=$request->t;
      $verifyLoginState=$this->verifyLoginState($userId,$t);
      if($verifyLoginState==2 || $verifyLoginState==3) return response($this->formatDataBody(null,'-1','登录已失效'));
      $categoryId=$request->categoryId;
      $isBan=$request->isBan;
      try {
        $bool= DB::table('tw_categories')->where('categoryId', $categoryId)->update(['isBan'=>$isBan]);
        return response($this->formatDataBody(null,'200','操作成功'));
      } catch (\Exception $e) {
        return response($this->formatDataBody(null,'0','失败，服务器错误'));
      }
    }
    //文章置顶与取消置顶
    public function topArticle(Request $request){
      $userId=$request->userId;
      $t=$request->t;
      $verifyLoginState=$this->verifyLoginState($userId,$t);
      if($verifyLoginState==2 || $verifyLoginState==3) return response($this->formatDataBody(null,'-1','登录已失效'));
      $articleId=$request->articleId;
      $isTop=$request->isTop;
      $updateAt=time();
      try {
        if($isTop==1)//如果是置顶，同步更新updateAt字段，以干扰排序
        $bool= DB::table('tw_articles')->where('articleId', $articleId)->update(['isTop'=>$isTop,'updateAt'=>$updateAt]);
        else $bool= DB::table('tw_articles')->where('articleId', $articleId)->update(['isTop'=>$isTop]);//如果是取消置顶,则不更新updateAt
        return response($this->formatDataBody(null,'200','操作成功'));
      } catch (\Exception $e) {
        return response($this->formatDataBody(null,'0','失败，服务器错误'));
      }
    }
    //文章启用停用
    public function banArticle(Request $request){
      $userId=$request->userId;
      $t=$request->t;
      $verifyLoginState=$this->verifyLoginState($userId,$t);
      if($verifyLoginState==2 || $verifyLoginState==3) return response($this->formatDataBody(null,'-1','登录已失效'));
      $articleId=$request->articleId;
      $isBan=$request->isBan;
      try {
        $bool= DB::table('tw_articles')->where('articleId', $articleId)->update(['isBan'=>$isBan]);
        return response($this->formatDataBody(null,'200','操作成功'));
      } catch (\Exception $e) {
        return response($this->formatDataBody(null,'0','失败，服务器错误'));
      }
    }
    //文章删除
    public function delArticle(Request $request){
      $userId=$request->userId;
      $t=$request->t;
      $verifyLoginState=$this->verifyLoginState($userId,$t);
      if($verifyLoginState==2 || $verifyLoginState==3) return response($this->formatDataBody(null,'-1','登录已失效'));
      $articleId=$request->articleId;
      try {
        $bool= DB::table('tw_articles')->where('articleId', $articleId)->update(['isDel'=>'1']);
        return response($this->formatDataBody(null,'200','操作成功'));
      } catch (\Exception $e) {
        return response($this->formatDataBody(null,'0','失败，服务器错误'));
      }
    }
    //栏目删除
    public function delCategory(Request $request){
      $userId=$request->userId;
      $t=$request->t;
      $verifyLoginState=$this->verifyLoginState($userId,$t);
      if($verifyLoginState==2 || $verifyLoginState==3) return response($this->formatDataBody(null,'-1','登录已失效'));
      $categoryId=$request->categoryId;
      try {
        $bool= DB::table('tw_categories')->where('categoryId', $categoryId)->update(['isDel'=>'1']);
        return response($this->formatDataBody(null,'200','操作成功'));
      } catch (\Exception $e) {
        return response($this->formatDataBody(null,'0','失败，服务器错误'));
      }
    }
    //布局元素删除
    public function delBlock(Request $request){
      $userId=$request->userId;
      $t=$request->t;
      $verifyLoginState=$this->verifyLoginState($userId,$t);
      if($verifyLoginState==2 || $verifyLoginState==3) return response($this->formatDataBody(null,'-1','登录已失效'));
      $blockId=$request->blockId;
      try {
        $bool= DB::table('tw_blocks')->where('blockId', $blockId)->update(['isDel'=>'1']);
        return response($this->formatDataBody(null,'200','操作成功'));
      } catch (\Exception $e) {
        return response($this->formatDataBody(null,'0','失败，服务器错误'));
      }
    }
    //管理文章列表
    public function getArticleList(Request $request){
      $userId=$request->userId;
      $t=$request->t;
      $verifyLoginState=$this->verifyLoginState($userId,$t);
      if($verifyLoginState==2 || $verifyLoginState==3) return response($this->formatDataBody(null,'-1','登录已失效'));
      $clientType=$request->clientType;
      $categoryId=$request->categoryId;
      $articleTitle=$request->articleTitle;
      $fromTime=$request->fromTime;
      $toTime=$request->toTime;
      $pageNum=$request->pageNum;
      $pageSize=$request->pageSize;
      if($pageSize==0)$pageSize=20;
      $conditionStr='clientType = ? and isDel = ? ';
      $conditionArr=[$clientType,'0'];
      if($articleTitle!='' && $articleTitle!=null){
        $conditionStr=$conditionStr.' and articleTitle like ? ';
        $conditionArr[]='%'.$articleTitle.'%';
      }
      if($fromTime>0){
        $conditionStr=$conditionStr.' and createAt > ? ';
        $conditionArr[]=$fromTime;
      }
      if($toTime>0){
        $conditionStr=$conditionStr.' and createAt < ? ';
        $conditionArr[]=$toTime;
      }
      if($categoryId>0 && $categoryId!=''){
        $conditionStr=$conditionStr.' and categoryId = ? ';
        $conditionArr[]=$categoryId;
      }
      if($pageNum<1)$pageNum=1;
      $count=DB::table('tw_articles')->whereRaw($conditionStr,$conditionArr)->count();
      $DBData=DB::table('tw_articles')->select('articleId', 'articleTitle','createAt','updateAt','isTop','isBan','categoryId','readCount','editReadCount')->whereRaw($conditionStr,$conditionArr)->orderby('isTop','desc')->orderby('updateAt','desc')->offset($pageNum*$pageSize-$pageSize)->limit($pageSize)->get();
      $DBData=$this->toArray($DBData);
      if(count($DBData)>0){
        switch ($clientType) {
          case '1':
            foreach ($DBData as $key => $value){
              $DBData[$key]['apiUrl']='http://api.solar_c.tanwin.cn/gln/module/article/articleNewInApp.html?articleId='.$value['articleId'];
            }
            break;
          case '2':
            foreach ($DBData as $key => $value){
              $DBData[$key]['apiUrl']='http://api.solar_c.tanwin.cn/gln/module/article/articleNewInApp.html?articleId='.$value['articleId'];
            }
            break;
          case '3':
            foreach ($DBData as $key => $value){
              $DBData[$key]['apiUrl']='http://www.tanwin.cn/infoT?id='.$value['articleId'];
            }
            break;
          default:
            foreach ($DBData as $key => $value){
              $DBData[$key]['apiUrl']='http://api.solar_c.tanwin.cn/gln/module/article/articleNewInApp.html?articleId='.$value['articleId'];
            }
            break;
        }
      }
      $result=[
        'count'=>$count,
        'list'=>$DBData,
      ];
      return response($this->formatDataBody($result));
    }
    //重定向下载并统计
    public function redirectDown(Request $request){
      $id=$request->id;
      $bool= DB::table('app_downCount')->where('id', $id)->update(['dCount'=>DB::raw("dcount + 1")]);
      return redirect('http://www.tanwin.cn/htmls/redirect_fwj.html');
    }
    //APP获取文章列表
    public function getArticleListByCode(Request $request){
      $appName=$request->appName;
      $accessKey=$request->accessKey;
      $verifyKeyState=$this->verifyKeyState($appName,$accessKey);
      if($verifyKeyState==2 || $verifyKeyState==3) return response($this->formatDataBody(null,'-1','无效的授权'));
      $clientType=$appName;
      $markCode=$request->markCode;
      $pageNum=$request->pageNum;
      $pageSize=$request->pageSize;
      if($pageSize==0)$pageSize=10;
      $conditionStr='clientType = ? and isDel = ? and isBan = ? ';
      $conditionArr=[$clientType,'0','0'];
      if($markCode!=null && $markCode!=''){
        $conditionStr=$conditionStr.' and markCode = ? ';
        $conditionArr[]=$markCode;
      }
      if($pageNum<1)$pageNum=1;
      $count=DB::table('tw_articles_view')->whereRaw($conditionStr,$conditionArr)->count();
      $DBData=DB::table('tw_articles_view')->select('articleId', 'articleTitle','mainPic','articleType','articleContract','linkUrl','videoUrl','videoLenth','createAt','updateAt','isTop','categoryId','readCount')->whereRaw($conditionStr,$conditionArr)->orderby('isTop','desc')->orderby('updateAt','desc')->offset($pageNum*$pageSize-$pageSize)->limit($pageSize)->get();
      $DBData=$this->toArray($DBData);
      if(count($DBData)>0){
        switch ($clientType) {
          case '1':
            foreach ($DBData as $key => $value){
              $DBData[$key]['apiUrl']='http://api.solar_c.tanwin.cn/gln/module/article/articleNewInApp.html?articleId='.$value['articleId'];
              $DBData[$key]['shareData']['shareTitle']=$value['articleTitle'];
              $DBData[$key]['shareData']['sharePic']=$value['mainPic'].'?x-oss-process=image/resize,w_180,h_180,m_fill';
              $DBData[$key]['shareData']['shareUrl']='http://api.solar_c.tanwin.cn/gln/module/article/articleNewInApp.html?articleId='.$value['articleId'];
              $DBData[$key]['shareData']['shareDesc']=$value['articleContract'];
            }
            break;
          case '2':
            foreach ($DBData as $key => $value){
              $DBData[$key]['apiUrl']='http://api.solar_c.tanwin.cn/gln/module/article/articleNewInApp.html?articleId='.$value['articleId'];
              $DBData[$key]['shareData']['shareTitle']=$value['articleTitle'];
              $DBData[$key]['shareData']['sharePic']=$value['mainPic'].'?x-oss-process=image/resize,w_180,h_180,m_fill';
              $DBData[$key]['shareData']['shareUrl']='http://api.solar_c.tanwin.cn/gln/module/article/articleNewInApp.html?articleId='.$value['articleId'];
              $DBData[$key]['shareData']['shareDesc']=$value['articleContract'];
            }
            break;
          case '3':
            foreach ($DBData as $key => $value){
              $DBData[$key]['apiUrl']='http://www.tanwin.cn/infoT?id='.$value['articleId'];
              $DBData[$key]['shareData']['shareTitle']=$value['articleTitle'];
              $DBData[$key]['shareData']['sharePic']=$value['mainPic'].'?x-oss-process=image/resize,w_180,h_180,m_fill';
              $DBData[$key]['shareData']['shareUrl']='http://api.solar_c.tanwin.cn/gln/module/article/articleNewInApp.html?articleId='.$value['articleId'];
              $DBData[$key]['shareData']['shareDesc']=$value['articleContract'];
            }
            break;
          default:
            foreach ($DBData as $key => $value){
              $DBData[$key]['apiUrl']='http://api.solar_c.tanwin.cn/gln/module/article/articleNewInApp.html?articleId='.$value['articleId'];
              $DBData[$key]['shareData']['shareTitle']=$value['articleTitle'];
              $DBData[$key]['shareData']['sharePic']=$value['mainPic'].'?x-oss-process=image/resize,w_180,h_180,m_fill';
              $DBData[$key]['shareData']['shareUrl']='http://api.solar_c.tanwin.cn/gln/module/article/articleNewInApp.html?articleId='.$value['articleId'];
              $DBData[$key]['shareData']['shareDesc']=$value['articleContract'];
            }
            break;
        }
      }
      $result=[
        'count'=>$count,
        'list'=>$DBData,
      ];
      return response($this->formatDataBody($result));
    }
    //APP获取文章详情
    public function getArticleContent(Request $request){
      $appName=$request->appName;
      $accessKey=$request->accessKey;
      $verifyKeyState=$this->verifyKeyState($appName,$accessKey);
      if($verifyKeyState==2 || $verifyKeyState==3) return response($this->formatDataBody(null,'-1','无效的授权'));
      $clientType=$appName;
      $articleId=$request->articleId;
      if($articleId==0 || !$articleId) return response($this->formatDataBody(null,'0','失败，文章不存在'));
      $data=DB::table('tw_articles_view')->whereRaw('articleId = ?',[$articleId])->first();
      $bool=DB::table('tw_articles')->whereRaw('articleId = ?',[$articleId])->update(['readCount'=>DB::raw("readCount + 1")]);
      if($data!=null){
        $data=$this->toArray($data);
        $data['shareData']=[
          'shareTitle'=>$data['articleTitle'],
          'shareUrl'=>'http://api.solar_c.tanwin.cn/gln/module/article/articleNew.html?articleId='.$data['articleId'].'&appName='.$appName,
          'sharePic'=>$data['mainPic'].'?x-oss-process=image/resize,w_180,h_180,m_fill',
          'shareDesc'=>$data['articleContract'],
        ];
        if($data['mainPic']==''||$data['mainPic']==null)$data['shareData']['sharePic']='';
        return response($this->formatDataBody($data,'200','操作成功'));
      }
      return response($this->formatDataBody($data,'0','数据不存在'));
    }
    //APP获取banner配置
    public function getBlockByCode(Request $request){
      $appName=$request->appName;
      $accessKey=$request->accessKey;
      $verifyKeyState=$this->verifyKeyState($appName,$accessKey);
      if($verifyKeyState==2 || $verifyKeyState==3) return response($this->formatDataBody(null,'-1','无效的授权'));
      $clientType=$appName;
      $markCode=$request->markCode;
      $conditionStr='clientType = ? and isDel = ? and isBan = ? ';
      $conditionArr=[$clientType,'0','0'];
      $conditionStr=$conditionStr.' and markCode = ? ';
      $conditionArr[]=$markCode;
      $DBData=DB::table('tw_blocks')->whereRaw($conditionStr,$conditionArr)->get();
      $DBData=$this->toArray($DBData);
      if(count($DBData)>0){
        $DBData[0]['blockData']=json_decode($DBData[0]['blockData'],true);
        if(count($DBData[0]['blockData'])>0){
          foreach ($DBData[0]['blockData'] as $key => $value) {
            if(isset($value['title']) && isset($value['sharePic']) && isset($value['desc']))
            $DBData[0]['blockData'][$key]['shareData']=[
              'shareTitle'=>$value['title'],
              'shareUrl'=>$value['href'],
              'sharePic'=>$value['sharePic'].'?x-oss-process=image/resize,w_180,h_180,m_fill',
              'shareDesc'=>$value['desc'],
            ];
            else $DBData[0]['blockData'][$key]['shareData']=[
              'shareTitle'=>'',
              'shareUrl'=>'',
              'sharePic'=>'',
              'shareDesc'=>'',
            ];
          }
        }
        return response($this->formatDataBody($DBData[0]['blockData']));
      }
      return response($this->formatDataBody(null,'0','失败，指定数据不存在'));
    }
    //APP获取配置
    public function appConfig(Request $request){
      $appName=$request->appName;
      $accessKey=$request->accessKey;
      $verifyKeyState=$this->verifyKeyState($appName,$accessKey);
      if($verifyKeyState==2 || $verifyKeyState==3) return response($this->formatDataBody(null,'-1','无效的授权'));
      $clientType=$appName;
      $markCode=$request->markCode;
      if($markCode==''||!$markCode)$markCode='d28ded62cb3463e57a992e769f9e576d';
      $conditionStr='clientType = ? and isDel = ? and isBan = ? ';
      $conditionArr=[$clientType,'0','0'];
      $conditionStr=$conditionStr.' and markCode = ? ';
      // print_r($conditionStr);
      $conditionArr[]=$markCode;
      // print_r($conditionArr);
      $bannerData=DB::table('tw_blocks')->whereRaw($conditionStr,$conditionArr)->get();
      if($bannerData!=false){
        $bannerData=$this->toArray($bannerData);
        if(isset($bannerData[0]))
        {
          $result['bannerData']=json_decode($bannerData[0]['blockData'],true);
          if(count($result['bannerData'])>0){
            foreach ($result['bannerData'] as $key => $value) {
              if(isset($value['title']) && isset($value['sharePic']) && isset($value['desc']))
              $result['bannerData'][$key]['shareData']=[
                'shareTitle'=>$value['title'],
                'shareUrl'=>$value['href'],
                'sharePic'=>$value['sharePic'].'?x-oss-process=image/resize,w_180,h_180,m_fill',
                'shareDesc'=>$value['desc'],
              ];
              else $result['bannerData'][$key]['shareData']=[
                'shareTitle'=>'',
                'shareUrl'=>'',
                'sharePic'=>'',
                'shareDesc'=>'',
              ];
            }
          }
        }
        else $result['bannerData']=[];
      }else {
        $result['bannerData']=[];
      }

      $result['video']=[
        'videoUrl'=>'http://img.tanwin.cn/tmpfile/2018-11-12/e537c1935d04f63331bd008d52c38498.mp4',
        'videoLenth'=>'02:14',
        'videoThumb'=>'http://img.tanwin.cn/tmpfile/2018-11-17/e641196d947d3133c549a065ae1301a7.jpg'
      ];
      $result['categories']=[
        [
          'name'=>'新商机',
          'config'=>[['categoryName'=>'新商机','markCode'=>'3634d8c958c8dbea61f2c905eb81a9a9']]
        ],
        [
          'name'=>'财富课堂',
          'config'=>[
            ['categoryName'=>'视频教程','markCode'=>'bb55e5b32b92caeb8c287d2f34a4e44e'],
            ['categoryName'=>'会销教程','markCode'=>'dcc58b5e05ccb79bf70d497723fdde19']
          ]
        ]
      ];
      $result['footerCategory']=['categoryName'=>'创富之路','markCode'=>'949d7a12a19fdb0554145bf99a7aad1a'];
      return response($this->formatDataBody($result));
    }
    //编辑文章,除活动外
    public function editArticle(Request $request){
      $userId=$request->userId;
      $t=$request->t;
      $verifyLoginState=$this->verifyLoginState($userId,$t);
      if($verifyLoginState==2 || $verifyLoginState==3) return response($this->formatDataBody(null,'-1','登录已失效'));
      $articleId=$request->articleId;
      if($articleId==0 || !$articleId) return response($this->formatDataBody(null,'0','失败，文章不存在'));
      $insertData['articleTitle']=$request->articleTitle;
      $insertData['categoryId']=$request->categoryId;
      $insertData['articleContract']=$request->articleContract;
      $insertData['articleContent']=$request->articleContent;
      $insertData['linkUrl']=$request->linkUrl;
      $insertData['articleType']=$request->articleType;
      $insertData['mainPic']=$request->mainPic;
      $insertData['videoUrl']=$request->videoUrl;
      $insertData['videoLenth']=$request->videoLenth;
      $insertData['sourceFrom']=$request->sourceFrom;
      $insertData['articleKeywords']=$request->articleKeywords;
      $insertData['articleDesc']=$request->articleDesc;
      $updateAt=time();
      $insertData['updateAt']=$updateAt;
      DB::beginTransaction();
      try {
        $bool= DB::table('tw_articles')->where('articleId', $articleId)->update($insertData);
        DB::commit();
        return response($this->formatDataBody($articleId,'200','操作成功'));
      } catch (\Exception $e) {
        DB::rollback();
        return response($this->formatDataBody(null,'0','失败，服务器错误'));
      }
      return response($this->formatDataBody(null,'0','失败，服务器错误'));
    }
    //文章回显
    public function getArticle(Request $request){
      $userId=$request->userId;
      $t=$request->t;
      $verifyLoginState=$this->verifyLoginState($userId,$t);
      if($verifyLoginState==2 || $verifyLoginState==3) return response($this->formatDataBody(null,'-1','登录已失效'));
      $articleId=$request->articleId;
      if($articleId==0 || !$articleId) return response($this->formatDataBody(null,'0','失败，文章不存在'));
      $data=DB::table('tw_articles')->whereRaw('articleId = ?',[$articleId])->first();
      if($data!=null){
        return response($this->formatDataBody($data,'200','操作成功'));
      }
      return response($this->formatDataBody($data,'0','数据不存在'));
    }
    //干扰文章阅读量
    public function editArticleReadCount(Request $request){
      $userId=$request->userId;
      $t=$request->t;
      $verifyLoginState=$this->verifyLoginState($userId,$t);
      if($verifyLoginState==2 || $verifyLoginState==3) return response($this->formatDataBody(null,'-1','登录已失效'));
      $articleId=$request->articleId;
      $editReadCount=$request->editReadCount;
      try {
        $bool= DB::table('tw_articles')->where('articleId', $articleId)->update(['editReadCount'=>$editReadCount]);
        return response($this->formatDataBody(null,'200','操作成功'));
      } catch (\Exception $e) {
        return response($this->formatDataBody(null,'0','失败，服务器错误'));
      }
    }
    //积分商城路列表
    public function skuList(Request $request){
      $userId=$request->userId;
      $t=$request->t;
      $verifyLoginState=$this->verifyLoginState($userId,$t);
      if($verifyLoginState==2 || $verifyLoginState==3) return response($this->formatDataBody(null,'-1','登录已失效'));
      // var_dump($this->SKULIST);
      // die();
      $rqUrl=JAVA_API_URI.SKULIST;
      $result=$this->curl->to($rqUrl)
      ->withOption('TIMEOUT', 10)
      ->post();
      $resultData=json_decode($result,true);
      if(isset($resultData['code']) && $resultData['code']==0){
        $resultData['code']=200;
        return response(json_encode($resultData));
      }
      return response($this->formatDataBody($resultData,'0','失败，上游服务器错误'));
    }

    //积分商品信息
    public function skuInfo(Request $request){
      $userId=$request->userId;
      $t=$request->t;
      $verifyLoginState=$this->verifyLoginState($userId,$t);
      if($verifyLoginState==2 || $verifyLoginState==3) return response($this->formatDataBody(null,'-1','登录已失效'));
      $rqUrl=JAVA_API_URI.SKUINFO;
      $rqData=['id'=>$request->id];
      $result=$this->curl->to($rqUrl)
      ->withData($rqData)
      ->withOption('TIMEOUT', 10)
      ->post();
      $resultData=json_decode($result,true);
      if(isset($resultData['code']) && $resultData['code']==0){
        $resultData['code']=200;
        return response(json_encode($resultData));
      }
      return response($this->formatDataBody($resultData,'0','失败，上游服务器错误'));
    }

    //积分商品信息编辑保存
    public function skuPut(Request $request){
      $userId=$request->userId;
      $t=$request->t;
      $verifyLoginState=$this->verifyLoginState($userId,$t);
      if($verifyLoginState==2 || $verifyLoginState==3) return response($this->formatDataBody(null,'-1','登录已失效'));
      $rqUrl=JAVA_API_URI.SKUPUT;
      $rqData=[
        'id'=>$request->id,
        'info'=>$request->info,
        'amount'=>$request->amount,
        'stockNum'=>$request->stockNum,
        'imgUrl'=>$request->imgUrl,
        'description'=>$request->description
    ];
      $result=$this->curl->to($rqUrl)
      ->withData($rqData)
      ->withOption('TIMEOUT', 10)
      ->post();
      $resultData=json_decode($result,true);
      if(isset($resultData['code']) && $resultData['code']==0){
        $resultData['code']=200;
        return response(json_encode($resultData));
      }
      return response($this->formatDataBody($resultData,'0','失败，上游服务器错误'));
    }

    //积分商品删除
    public function skuDel(Request $request){
      $userId=$request->userId;
      $t=$request->t;
      $verifyLoginState=$this->verifyLoginState($userId,$t);
      if($verifyLoginState==2 || $verifyLoginState==3) return response($this->formatDataBody(null,'-1','登录已失效'));
      $rqUrl=JAVA_API_URI.SKUDEL;
      $rqData=['id'=>$request->id];
      $result=$this->curl->to($rqUrl)
      ->withData($rqData)
      ->withOption('TIMEOUT', 10)
      ->post();
      $resultData=json_decode($result,true);
      if(isset($resultData['code']) && $resultData['code']==0){
        $resultData['code']=200;
        return response(json_encode($resultData));
      }
      return response($this->formatDataBody($resultData,'0','失败，上游服务器错误'));
    }

    //积分商品兑换记录
    public function skuLog(Request $request){
      $userId=$request->userId;
      $t=$request->t;
      $verifyLoginState=$this->verifyLoginState($userId,$t);
      if($verifyLoginState==2 || $verifyLoginState==3) return response($this->formatDataBody(null,'-1','登录已失效'));
      $rqUrl=JAVA_API_URI.SKULOG;
      $rqData=[
        'startDate'=>$request->startDate,
        'endDate'=>$request->endDate,
        'info'=>$request->info,
        'nowpage'=>$request->nowpage,
        'pagesize'=>$request->pagesize
    ];
      $result=$this->curl->to($rqUrl)
      ->withData($rqData)
      ->withOption('TIMEOUT', 10)
      ->post();
      $resultData=json_decode($result,true);
      if(isset($resultData['code']) && $resultData['code']==0){
        $resultData['code']=200;
        return response(json_encode($resultData));
      }
      return response($this->formatDataBody($resultData,'0','失败，上游服务器错误'));
    }

    //用户管理分页列表
    public function userList(Request $request){
      $userId=$request->userId;
      $t=$request->t;
      $verifyLoginState=$this->verifyLoginState($userId,$t);
      if($verifyLoginState==2 || $verifyLoginState==3) return response($this->formatDataBody(null,'-1','登录已失效'));
      $rqUrl=JAVA_API_URI.USERLIST;
      $rqData=[
        'startDate'=>$request->startDate,
        'endDate'=>$request->endDate,
        'sort'=>$request->sort,
        'order'=>$request->order,
        'info'=>$request->info,
        'nowpage'=>$request->nowpage,
        'pagesize'=>$request->pagesize,
        'loginCount'=>$request->loginCount,
        'isCreator'=>$request->isCreator,
        'grade'=>$request->grade,
    ];
      $result=$this->curl->to($rqUrl)
      ->withData($rqData)
      ->withOption('TIMEOUT', 10)
      ->post();
      $resultData=json_decode($result,true);
      if(isset($resultData['code']) && $resultData['code']==0){
        $resultData['code']=200;
        return response(json_encode($resultData));
      }
      return response($this->formatDataBody($resultData,'0','失败，上游服务器错误'));
    }

    //用户管理列表导出
    public function userExport(Request $request){
      $userId=$request->userId;
      $t=$request->t;
      $verifyLoginState=$this->verifyLoginState($userId,$t);
      if($verifyLoginState==2 || $verifyLoginState==3) return response($this->formatDataBody(null,'-1','登录已失效'));
      $rqUrl=JAVA_API_URI.USEREXPORT;
      $rqData=[
        'startDate'=>$request->startDate,
        'endDate'=>$request->endDate,
        'info'=>$request->info
    ];
      $result=$this->curl->to($rqUrl)
      ->withData($rqData)
      ->withOption('TIMEOUT', 10)
      ->post();
      $resultData=json_decode($result,true);
      if(isset($resultData['code']) && $resultData['code']==0){
        $resultData['code']=200;
        return response(json_encode($resultData));
      }
      return response($this->formatDataBody($resultData,'0','失败，上游服务器错误'));
    }

    //用户粮票
    public function userPoint(Request $request){
      $userId=$request->userId;
      $t=$request->t;
      $verifyLoginState=$this->verifyLoginState($userId,$t);
      if($verifyLoginState==2 || $verifyLoginState==3) return response($this->formatDataBody(null,'-1','登录已失效'));
      $rqUrl=JAVA_API_URI.USERPOINTUPDATE;
      $rqData=[
        'ids'=>$request->ids,
        'reason'=>$request->reason,
        'point'=>$request->point
    ];
      $result=$this->curl->to($rqUrl)
      ->withData($rqData)
      ->withOption('TIMEOUT', 10)
      ->post();
      $resultData=json_decode($result,true);
      if(isset($resultData['code']) && $resultData['code']==0){
        $resultData['code']=200;
        return response(json_encode($resultData));
      }
      return response($this->formatDataBody($resultData,'0','失败，上游服务器错误'));
    }

    //活动列表
    public function activityList(Request $request){
      $userId=$request->userId;
      $t=$request->t;
      $verifyLoginState=$this->verifyLoginState($userId,$t);
      if($verifyLoginState==2 || $verifyLoginState==3) return response($this->formatDataBody(null,'-1','登录已失效'));
      $rqUrl=JAVA_API_URI.ACTIVITYLIST;
      $rqData=[
        'startTime'=>$request->startTime,
        'endTime'=>$request->endTime,
        'search'=>$request->search,
        'pageNo'=>$request->pageNo,
        'pageSize'=>$request->pageSize
      ];
      $result=$this->curl->to($rqUrl)
      ->withData($rqData)
      ->withOption('TIMEOUT', 10)
      ->post();
      $resultData=json_decode($result,true);
      if(isset($resultData['code']) && $resultData['code']==0){
        $resultData['code']=200;
        return response(json_encode($resultData));
      }
      return response($this->formatDataBody($resultData,'0','失败，上游服务器错误'));
    }

    //活动详情
    public function activityInfo(Request $request){
      $userId=$request->userId;
      $t=$request->t;
      $verifyLoginState=$this->verifyLoginState($userId,$t);
      if($verifyLoginState==2 || $verifyLoginState==3) return response($this->formatDataBody(null,'-1','登录已失效'));
      $rqUrl=JAVA_API_URI.ACTIVITYGET;
      $rqData=[
        'id'=>$request->id
    ];
      $result=$this->curl->to($rqUrl)
      ->withData($rqData)
      ->withOption('TIMEOUT', 10)
      ->post();
      $resultData=json_decode($result,true);
      if(isset($resultData['code']) && $resultData['code']==0){
        $resultData['code']=200;
        return response(json_encode($resultData));
      }
      return response($this->formatDataBody($resultData,'0','失败，上游服务器错误'));
    }

    //活动发布编辑
    public function activityUpdate(Request $request){
      $userId=$request->userId;
      $t=$request->t;
      $verifyLoginState=$this->verifyLoginState($userId,$t);
      if($verifyLoginState==2 || $verifyLoginState==3) return response($this->formatDataBody(null,'-1','登录已失效'));
      $rqUrl=JAVA_API_URI.ACTIVITYPUT;
      $rqData=[
        'id'=>$request->id,
        'name'=>$request->name,
        'applyDateStart'=>$request->applyDateStart,
        'applyDateEnd'=>$request->applyDateEnd,
        'address'=>$request->address,
        'maxCount'=>$request->maxCount,
        'longitude'=>$request->longitude,
        'latitude'=>$request->latitude,
        'content'=>$request->content,
        'picUrl'=>$request->url
    ];
      $result=$this->curl->to($rqUrl)
      ->withData($rqData)
      ->withOption('TIMEOUT', 10)
      ->post();
      // var_dump($result);
      // die();
      $resultData=json_decode($result,true);
      if(isset($resultData['code']) && $resultData['code']==0){
        $resultData['code']=200;
        return response(json_encode($resultData));
      }
      return response($this->formatDataBody($resultData,'0','失败，上游服务器错误'));
    }

    //活动关闭
    public function activityClose(Request $request){
      $userId=$request->userId;
      $t=$request->t;
      $verifyLoginState=$this->verifyLoginState($userId,$t);
      if($verifyLoginState==2 || $verifyLoginState==3) return response($this->formatDataBody(null,'-1','登录已失效'));
      $rqUrl=JAVA_API_URI.ACTIVITYCLOSE;
      $rqData=[
        'id'=>$request->id
    ];
      $result=$this->curl->to($rqUrl)
      ->withData($rqData)
      ->withOption('TIMEOUT', 10)
      ->post();
      $resultData=json_decode($result,true);
      if(isset($resultData['code']) && $resultData['code']==0){
        $resultData['code']=200;
        return response(json_encode($resultData));
      }
      return response($this->formatDataBody($resultData,'0','失败，上游服务器错误'));
    }

    //活动报名列表
    public function activityData(Request $request){
      $userId=$request->userId;
      $t=$request->t;
      $verifyLoginState=$this->verifyLoginState($userId,$t);
      if($verifyLoginState==2 || $verifyLoginState==3) return response($this->formatDataBody(null,'-1','登录已失效'));
      $rqUrl=JAVA_API_URI.ACTIVITYDATA;
      $rqData=[
        'id'=>$request->id,
        'pageNo'=>$request->pageNo,
        'pageSize'=>$request->pageSize
    ];
      $result=$this->curl->to($rqUrl)
      ->withData($rqData)
      ->withOption('TIMEOUT', 10)
      ->post();
      $resultData=json_decode($result,true);
      if(isset($resultData['code']) && $resultData['code']==0){
        $resultData['code']=200;
        return response(json_encode($resultData));
      }
      return response($this->formatDataBody($resultData,'0','失败，上游服务器错误'));
    }

    //下载列表
    public function downList(Request $request){
      $userId=$request->userId;
      $t=$request->t;
      $verifyLoginState=$this->verifyLoginState($userId,$t);
      if($verifyLoginState==2 || $verifyLoginState==3) return response($this->formatDataBody(null,'-1','登录已失效'));
      $rqUrl=TEST_JAVA_API_URI.DOWNLIST;
      $rqData['type']=$request->type;
      $rqData['fileType']=$request->fileType;
      $rqData['startTime']=$request->startTime*1000;
      $rqData['endTime']=$request->endTime*1000;
      if($rqData['startTime']==0)unset($rqData['startTime']);
      if($rqData['endTime']==0)unset($rqData['endTime']);
      $rqData['name']=$request->name;
      $rqData['from']=$request->from;
      if($rqData['from']==null)unset($rqData['from']);
      $rqData['pageNo']=$request->pageNo;
      $rqData['pageSize']=$request->pageSize;
      $result=$this->curl->to($rqUrl)
      ->withData($rqData)
      ->withOption('TIMEOUT', 10)
      ->post();
      $resultData=json_decode($result,true);
      // print_r($result);
      if(isset($resultData['code']) && $resultData['code']=='0'){
        $resultData['code']='0';
        return response(json_encode($resultData));
      }
      if(!isset($resultData['code']))$resultData['code']='-1';
      return response($this->formatDataBody($resultData,'0','失败，上游服务器错误',$resultData['code']));
    }

    //下载启用禁用
    public function downEnable(Request $request){
      $userId=$request->userId;
      $t=$request->t;
      $verifyLoginState=$this->verifyLoginState($userId,$t);
      if($verifyLoginState==2 || $verifyLoginState==3) return response($this->formatDataBody(null,'-1','登录已失效'));
      $rqUrl=TEST_JAVA_API_URI.DOWNENABLE;
      $rqData['id']=$request->id;
      $rqData['enable']=$request->enable;
      $result=$this->curl->to($rqUrl)
      ->withData($rqData)
      ->withOption('TIMEOUT', 10)
      ->post();
      $resultData=json_decode($result,true);
      // print_r($result);
      if(isset($resultData['code']) && $resultData['code']=='0'){
        $resultData['code']='0';
        return response(json_encode($resultData));
      }
      if(!isset($resultData['code']))$resultData['code']='-1';
      return response($this->formatDataBody($resultData,'0','失败，上游服务器错误',$resultData['code']));
    }

    //下载回显
    public function downInfo(Request $request){
      $userId=$request->userId;
      $t=$request->t;
      $verifyLoginState=$this->verifyLoginState($userId,$t);
      if($verifyLoginState==2 || $verifyLoginState==3) return response($this->formatDataBody(null,'-1','登录已失效'));
      $rqUrl=TEST_JAVA_API_URI.DOWNINFO;
      $rqData['id']=$request->id;
      $result=$this->curl->to($rqUrl)
      ->withData($rqData)
      ->withOption('TIMEOUT', 10)
      ->post();
      $resultData=json_decode($result,true);
      // print_r($result);
      if(isset($resultData['code']) && $resultData['code']=='0'){
        $resultData['code']='0';
        return response(json_encode($resultData));
      }
      if(!isset($resultData['code']))$resultData['code']='-1';
      return response($this->formatDataBody($resultData,'0','失败，上游服务器错误',$resultData['code']));
    }

    //下载置顶
    public function downTop(Request $request){
      $userId=$request->userId;
      $t=$request->t;
      $verifyLoginState=$this->verifyLoginState($userId,$t);
      if($verifyLoginState==2 || $verifyLoginState==3) return response($this->formatDataBody(null,'-1','登录已失效'));
      $rqUrl=TEST_JAVA_API_URI.DOWNTOP;
      $rqData['id']=$request->id;
      $rqData['top']=$request->top;
      $result=$this->curl->to($rqUrl)
      ->withData($rqData)
      ->withOption('TIMEOUT', 10)
      ->post();
      $resultData=json_decode($result,true);
      // print_r($result);
      if(isset($resultData['code']) && $resultData['code']=='0'){
        $resultData['code']='0';
        return response(json_encode($resultData));
      }
      if(!isset($resultData['code']))$resultData['code']='-1';
      return response($this->formatDataBody($resultData,'0','失败，上游服务器错误',$resultData['code']));
    }

    //下载删除
    public function downDelete(Request $request){
      $userId=$request->userId;
      $t=$request->t;
      $verifyLoginState=$this->verifyLoginState($userId,$t);
      if($verifyLoginState==2 || $verifyLoginState==3) return response($this->formatDataBody(null,'-1','登录已失效'));
      $rqUrl=TEST_JAVA_API_URI.DOWNDELETE;
      $rqData['id']=$request->id;
      $result=$this->curl->to($rqUrl)
      ->withData($rqData)
      ->withOption('TIMEOUT', 10)
      ->post();
      $resultData=json_decode($result,true);
      // print_r($result);
      if(isset($resultData['code']) && $resultData['code']=='0'){
        $resultData['code']='0';
        return response(json_encode($resultData));
      }
      if(!isset($resultData['code']))$resultData['code']='-1';
      return response($this->formatDataBody($resultData,'0','失败，上游服务器错误',$resultData['code']));
    }

    //添加资料
    public function downAdd(Request $request){
      $userId=$request->userId;
      $t=$request->t;
      $verifyLoginState=$this->verifyLoginState($userId,$t);
      if($verifyLoginState==2 || $verifyLoginState==3) return response($this->formatDataBody(null,'-1','登录已失效'));
      $rqUrl=TEST_JAVA_API_URI.DOWNADD;
      $rqData['type']=$request->type;
      $rqData['fileType']=$request->fileType;
      $rqData['name']=$request->name;
      $rqData['desc']=$request->desc;
      $rqData['coverUrl']=$request->coverUrl;
      $rqData['dataUrl']=$request->dataUrl;
      $rqData['size']=$request->size;
      $rqData['length']=$request->length;
      $rqData['width']=$request->width;
      $rqData['content']=$request->content;
      $rqData['from']=$request->from;
      if($rqData['from']==null)unset($rqData['from']);
      $result=$this->curl->to($rqUrl)
      ->withData($rqData)
      ->withOption('TIMEOUT', 10)
      ->post();
      $resultData=json_decode($result,true);
      // print_r($result);
      if(isset($resultData['code']) && $resultData['code']=='0'){
        $resultData['code']='0';
        return response(json_encode($resultData));
      }
      if(!isset($resultData['code']))$resultData['code']='-1';
      return response($this->formatDataBody($resultData,'0','失败，上游服务器错误',$resultData['code']));
    }

    //编辑下载
    public function downEdit(Request $request){
      $userId=$request->userId;
      $t=$request->t;
      $verifyLoginState=$this->verifyLoginState($userId,$t);
      if($verifyLoginState==2 || $verifyLoginState==3) return response($this->formatDataBody(null,'-1','登录已失效'));
      $rqUrl=TEST_JAVA_API_URI.DOWNEDIT;
      $rqData['id']=$request->id;
      $rqData['type']=$request->type;
      $rqData['fileType']=$request->fileType;
      $rqData['name']=$request->name;
      $rqData['desc']=$request->desc;
      $rqData['coverUrl']=$request->coverUrl;
      $rqData['dataUrl']=$request->dataUrl;
      $rqData['size']=$request->size;
      $rqData['length']=$request->length;
      $rqData['width']=$request->width;
      $rqData['content']=$request->content;
      $rqData['from']=$request->from;
      if($rqData['from']==null)unset($rqData['from']);
      $result=$this->curl->to($rqUrl)
      ->withData($rqData)
      ->withOption('TIMEOUT', 10)
      ->post();
      $resultData=json_decode($result,true);
      // print_r($result);
      if(isset($resultData['code']) && $resultData['code']=='0'){
        $resultData['code']='0';
        return response(json_encode($resultData));
      }
      if(!isset($resultData['code']))$resultData['code']='-1';
      return response($this->formatDataBody($resultData,'0','失败，上游服务器错误',$resultData['code']));
    }

    //秒杀列表
    public function seckillList(Request $request){
      $userId=$request->userId;
      $t=$request->t;
      $verifyLoginState=$this->verifyLoginState($userId,$t);
      if($verifyLoginState==2 || $verifyLoginState==3) return response($this->formatDataBody(null,'-1','登录已失效'));
      $rqUrl=TEST_JAVA_API_URI.SECKILLLIST;
      $rqData['pageNo']=$request->pageNo;
      $rqData['pageSize']=$request->pageSize;
      $result=$this->curl->to($rqUrl)
      ->withData($rqData)
      ->withOption('TIMEOUT', 10)
      ->post();
      $resultData=json_decode($result,true);
      if(isset($resultData['code']) && $resultData['code']=='0'){
        $resultData['code']='0';
        foreach ($resultData['data']['rows'] as $key => $value) {
          $resultData['data']['rows'][$key]['startTime']=substr($value['startTime'],0,10);
          $resultData['data']['rows'][$key]['endTime']=substr($value['endTime'],0,10);
        }
        return response(json_encode($resultData));
      }
      if(!isset($resultData['code']))$resultData['code']='-1';
      return response($this->formatDataBody($resultData,'0','失败，上游服务器错误',$resultData['code']));
    }

    //添加秒杀
    public function seckillAdd(Request $request){
      $userId=$request->userId;
      $t=$request->t;
      $verifyLoginState=$this->verifyLoginState($userId,$t);
      if($verifyLoginState==2 || $verifyLoginState==3) return response($this->formatDataBody(null,'-1','登录已失效'));
      $rqUrl=TEST_JAVA_API_URI.SECKILLADD;
      $rqData['productId']=$request->productId;
      $rqData['title']=$request->title;
      $rqData['startTime']=$request->startTime;
      $rqData['endTime']=$request->endTime;
      $rqData['sortNo']=$request->sortNo;
      $rqData['seckillPrice']=$request->seckillPrice;
      $rqData['restNum']=$request->restNum;
      $rqData['otherNum']=$request->otherNum;
      $rqData['phase']=$request->phase;
      $rqData['coverPicUrl']=$request->coverPicUrl;
      $result=$this->curl->to($rqUrl)
      ->withData($rqData)
      ->withOption('TIMEOUT', 10)
      ->post();
      // print_r($result);
      $resultData=json_decode($result,true);
      if(isset($resultData['code']) && $resultData['code']=='0'){
        $resultData['code']='0';
        return response(json_encode($resultData));
      }
      if(!isset($resultData['code']))$resultData['code']='-1';
      return response($this->formatDataBody($resultData,'0','失败，上游服务器错误',$resultData['code']));
    }

    //秒杀详情seckillInfo
    public function seckillInfo(Request $request){
      $userId=$request->userId;
      $t=$request->t;
      $verifyLoginState=$this->verifyLoginState($userId,$t);
      if($verifyLoginState==2 || $verifyLoginState==3) return response($this->formatDataBody(null,'-1','登录已失效'));
      $rqUrl=TEST_JAVA_API_URI.SECKILLINFO;
      $rqData['id']=$request->id;
      $result=$this->curl->to($rqUrl)
      ->withData($rqData)
      ->withOption('TIMEOUT', 10)
      ->post();
      $resultData=json_decode($result,true);
      if(isset($resultData['code']) && $resultData['code']=='0'){
        $resultData['code']='0';
        $resultData['data']['startTime']=substr($resultData['data']['startTime'],0,10);
        $resultData['data']['endTime']=substr($resultData['data']['endTime'],0,10);
        return response(json_encode($resultData));
      }
      if(!isset($resultData['code']))$resultData['code']='-1';
      return response($this->formatDataBody($resultData,'0','失败，上游服务器错误',$resultData['code']));
    }

    //编辑秒杀
    public function seckillEdit(Request $request){
      $userId=$request->userId;
      $t=$request->t;
      $verifyLoginState=$this->verifyLoginState($userId,$t);
      if($verifyLoginState==2 || $verifyLoginState==3) return response($this->formatDataBody(null,'-1','登录已失效'));
      $rqUrl=TEST_JAVA_API_URI.SECKILLEDIT;
      $rqData['id']=$request->id;
      $rqData['productId']=$request->productId;
      $rqData['title']=$request->title;
      $rqData['startTime']=$request->startTime;
      $rqData['endTime']=$request->endTime;
      $rqData['sortNo']=$request->sortNo;
      $rqData['seckillPrice']=$request->seckillPrice;
      $rqData['restNum']=$request->restNum;
      $rqData['otherNum']=$request->otherNum;
      $rqData['phase']=$request->phase;
      $rqData['coverPicUrl']=$request->coverPicUrl;
      $result=$this->curl->to($rqUrl)
      ->withData($rqData)
      ->withOption('TIMEOUT', 10)
      ->post();
      $resultData=json_decode($result,true);
      if(isset($resultData['code']) && $resultData['code']=='0'){
        $resultData['code']='0';
        return response(json_encode($resultData));
      }
      if(!isset($resultData['code']))$resultData['code']='-1';
      return response($this->formatDataBody($resultData,'0','失败，上游服务器错误',$resultData['code']));
    }

    //删除秒杀
    public function seckillDelete(Request $request){
      $userId=$request->userId;
      $t=$request->t;
      $verifyLoginState=$this->verifyLoginState($userId,$t);
      if($verifyLoginState==2 || $verifyLoginState==3) return response($this->formatDataBody(null,'-1','登录已失效'));
      $rqUrl=TEST_JAVA_API_URI.SECKILLDELETE;
      $rqData['id']=$request->id;
      $result=$this->curl->to($rqUrl)
      ->withData($rqData)
      ->withOption('TIMEOUT', 10)
      ->post();
      $resultData=json_decode($result,true);
      if(isset($resultData['code']) && $resultData['code']=='0'){
        $resultData['code']='0';
        return response(json_encode($resultData));
      }
      if(!isset($resultData['code']))$resultData['code']='-1';
      return response($this->formatDataBody($resultData,'0','失败，上游服务器错误',$resultData['code']));
    }

    //创建订单
    public function createBill(Request $request){
      $token=$request->userToken;
      $userId=$request->userId;
      $billAmount=$request->billAmount;
      $billAddress=$request->billAddress;
      $billContractor=$request->billContractor;
      $billPhone=$request->billPhone;
      $time=time();
      $userVerify=DB::table('user')->whereRaw('userId = ? and userToken= ?',[$userId,$token])->first();
      if(json_encode($userVerify)==null){
        return response($this->formatDataBody(false,999,'登录信息有误，请重新登录'));
      }
      DB::beginTransaction();
      try {
        $billData=$request->billData;
        $listData=json_decode($billData,true);
        // var_dump($listData);
        if(count($listData)>0)
        // if(1==1)
        {
          $billNumber = date('Ymd').str_pad(mt_rand(1, 99999), 5, '0', STR_PAD_LEFT);
          $bill = bills::insertGetId(['billList' => $billData,'userId'=>$userId ,'createTime'=>$time ,'billAmount'=>$billAmount ,'billAddress'=>$billAddress ,'billContractor'=>$billContractor ,'billPhone'=>$billPhone,'billNumber'=>$billNumber]);
          $newId=$bill;
          foreach ($listData as $key => $value) {
            $arrInsert[$key]=$value;
            $arrInsert[$key]['billId']=$newId;
            // $arrInsert[$key]['skuId']=$value['skuId'];
            // $arrInsert[$key]['skuAmount']=$value['skuAmount'];
            // $arrInsert[$key]['skuPrice']=$value['skuPrice'];
            // $arrInsert[$key]['skuUnit']=$value['skuUnit'];
            // $arrInsert[$key]['skuImg']=$value['skuImg'];
            // $arrInsert[$key]['skuName']=$value['skuName'];
            $arrInsert[$key]['createTime']=$time;
          }
          // var_dump($arrInsert);
          $bool=DB::table('billSkuRelation')->insert($arrInsert);
          // var_dump($bool);
          DB::commit();
          return response($this->formatDataBody(['billId'=>$newId]));
        }else{
          DB::rollback();
          return response($this->formatDataBody(false,0,'请勿提交空订单'));
        }
      } catch (\Exception $e) {
        DB::rollback();
        return response($this->formatDataBody(false,0,$e));
      }
    }
    //获取历史订单
    public function getBillList(Request $request){
      $token=$request->userToken;
      $userId=$request->userId;
      $pageNum=$request->pageNum;
      $userVerify=DB::table('user')->whereRaw('userId = ? and userToken= ?',[$userId,$token])->first();
      if(json_encode($userVerify)==null){
        return response($this->formatDataBody(false,999,'登录信息有误，请重新登录'));
      }
      if($pageNum==null||!isset($pageNum)){
        $pageNum=0;
      }
      $DBData=DB::table('bills')->where('userId',$userId)->orderby('billId','desc')->offset($pageNum*6)->limit(6)->get();
      if(count($DBData)>0){
        foreach ($DBData as $key => $value) {
          $value->billList=json_decode($value->billList);
        }
      }
      return response($this->formatDataBody($DBData));
    }
    //获取地址列表
    public function addressList(Request $request){
      $token=$request->userToken;
      $userId=$request->userId;
      $userVerify=DB::table('user')->whereRaw('userId = ? and userToken= ?',[$userId,$token])->first();
      if(json_encode($userVerify)==null){
        return response($this->formatDataBody(false,999,'登录信息有误，请重新登录'));
      }
      $DBData=DB::table('address')->where(['userId'=>$userId])->orderby('addressId','desc')->get();
      // $DBData=json_encode($DBData);
      return response($this->formatDataBody($DBData));
    }
    //创建地址
    public function createAddress(Request $request){
      $token=$request->userToken;
      $userId=$request->userId;
      $data['userId']=$userId;
      $data['contractName']=$request->contractName;
      $data['contractPhone']=$request->contractPhone;
      $data['province']=$request->province;
      $data['city']=$request->city;
      $data['district']=$request->district;
      $data['addressDetail']=$request->addressDetail;
      $userVerify=DB::table('user')->whereRaw('userId = ? and userToken= ?',[$userId,$token])->first();
      if(json_encode($userVerify)==null){
        return response($this->formatDataBody(false,999,'登录信息有误，请重新登录'));
      }
      DB::beginTransaction();
      try {
        $bool=DB::table('address')->insert($data);
        DB::commit();
        return response($this->formatDataBody($bool));
      } catch (\Exception $e) {
        DB::rollback();
        return response($this->formatDataBody(false,207,$e));
      }
    }
    //修改昵称
    public function editUserName(Request $request){
      $token=$request->userToken;
      $userId=$request->userId;
      $userName=$request->userName;
      $userVerify=DB::table('user')->whereRaw('userId = ? and userToken= ?',[$userId,$token])->first();
      if(json_encode($userVerify)==null){
        return response($this->formatDataBody(false,999,'登录信息有误，请重新登录'));
      }
      DB::beginTransaction();
      try {
        $bool= DB::table('user')->where('userId', $userId)->update(['userName'=>$userName]);
        DB::commit();
        if($bool) return response($this->formatDataBody($bool));
        else return response($this->formatDataBody(false,208,'修改失败，请重试'));
      } catch (\Exception $e) {
        DB::rollback();
        return response($this->formatDataBody(false,207,$e));
      }
    }
    //获取昵称
    public function getUserName(Request $request){
      $token=$request->userToken;
      $userId=$request->userId;
      $userVerify=DB::table('user')->whereRaw('userId = ? and userToken= ?',[$userId,$token])->first();
      if(json_encode($userVerify)==null){
        return response($this->formatDataBody(false,999,'登录信息有误，请重新登录'));
      }
      $data=DB::table('user')->where(['userId'=>$userId])->first();
      $DBData=['userName'=>$data->userName];
      return response($this->formatDataBody($DBData));
    }
    //获取实名状态
    public function getRealNameState(Request $request){
      $token=$request->userToken;
      $userId=$request->userId;
      $userVerify=DB::table('user')->whereRaw('userId = ? and userToken= ?',[$userId,$token])->first();
      if(json_encode($userVerify)==null){
        return response($this->formatDataBody(false,999,'登录信息有误，请重新登录'));
      }
      $data=DB::table('user')->where(['userId'=>$userId])->first();
      $DBData=['realNameState'=>$data->realNameState];
      return response($this->formatDataBody($DBData));
    }
    //实名认证提交
    public function editRealNameState(Request $request){
      $token=$request->userToken;
      $userId=$request->userId;
      $data['userId']=$userId;
      $data['realName']=$request->realName;
      $data['IDNumber']=$request->IDNumber;
      $userVerify=DB::table('user')->whereRaw('userId = ? and userToken= ?',[$userId,$token])->first();
      if(json_encode($userVerify)==null){
        return response($this->formatDataBody(false,999,'登录信息有误，请重新登录'));
      }
      DB::beginTransaction();
      try {
        $bool=DB::table('realName')->insert($data);
        if($bool){
          $result=DB::table('user')->where(['userId'=>$userId])->update(['realNameState'=>1]);
        }
        DB::commit();
        if($result) return response($this->formatDataBody($result));
        else return response($this->formatDataBody(false,208,'提交失败'));
      } catch (\Exception $e) {
        DB::rollback();
        return response($this->formatDataBody(false,207,$e));
      }
    }
    //修改绑定手机
    public function editUserPhone(Request $request){
      $token=$request->userToken;
      $userId=$request->userId;
      // $data['userId']=$userId;
      $data['oldPhone']=$request->oldPhone;
      $data['oldCode']=$request->oldCode;
      $data['newPhone']=$request->newPhone;
      $data['newCode']=$request->newCode;
      $time=time();
      $userVerify=DB::table('user')->whereRaw('userId = ? and userToken= ?',[$userId,$token])->first();
      if(json_encode($userVerify)==null){
        return response($this->formatDataBody(false,999,'登录信息有误，请重新登录'));
      }
      $verifyNewPhone=DB::table('user')->where(['userPhone'=>$data['newPhone']])->first();
      if($verifyNewPhone!=null && isset($verifyNewPhone->userId)) return response($this->formatDataBody(false,901,'新的手机号已注册'));
      $verifyCodeOld=DB::table('sms_code_log')->whereRaw('phone = ? and code= ?',[$data['oldPhone'],$data['oldCode']])->orderby('id','desc')->first();
      $verifyCodeNew=DB::table('sms_code_log')->whereRaw('phone = ? and code= ?',[$data['newPhone'],$data['newCode']])->orderby('id','desc')->first();
      if($verifyCodeOld!==null && $time-$verifyCodeOld->create_time<=900 && $verifyCodeNew!==null && $time-$verifyCodeNew->create_time<=900){
        DB::beginTransaction();
        try {
            $result=DB::table('user')->where(['userId'=>$userId])->update(['userPhone'=>$data['newPhone']]);
            DB::commit();
            if($result) return response($this->formatDataBody($result));
            else return response($this->formatDataBody(false,208,'修改失败'));
        } catch (\Exception $e) {
          DB::rollback();
          return response($this->formatDataBody(false,207,$e));
        }
      }else {
        return response($this->formatDataBody(false,202,'验证码不正确或已过期'));
      }
    }
    //修改地址
    public function editAddress(Request $request){
      $token=$request->userToken;
      $userId=$request->userId;
      $addressId=$request->addressId;
      $data['userId']=$userId;
      $data['contractName']=$request->contractName;
      $data['contractPhone']=$request->contractPhone;
      $data['province']=$request->province;
      $data['city']=$request->city;
      $data['district']=$request->district;
      $data['addressDetail']=$request->addressDetail;
      $userVerify=DB::table('user')->whereRaw('userId = ? and userToken= ?',[$userId,$token])->first();
      if(json_encode($userVerify)==null){
        return response($this->formatDataBody(false,999,'登录信息有误，请重新登录'));
      }
      DB::beginTransaction();
      try {
        $bool= DB::table('address')->where('addressId', $addressId)->update($data);
        DB::commit();
        if($bool) return response($this->formatDataBody($bool));
        else return response($this->formatDataBody(false,208,'地址修改失败，请重试'));
      } catch (\Exception $e) {
        DB::rollback();
        return response($this->formatDataBody(false,207,$e));
      }
    }
    //获取验证码
    public function getCode(Request $request){
      $userPhone=$request->userPhone;
      $code = mt_rand(100000, 999999);
      $type=$request->type;
      // if($type==null || $type==0)$msgModelCode='SMS_133225048';
      if($type==null || $type==0)$msgModelCode='SMS_137422571';
      else $msgModelCode='SMS_137422571';
      $time=time();
      try {
        $result = $this->sendSms($userPhone,"阿里云短信测试专用",$msgModelCode,$code);
        DB::table('sms_code_log')->insert(['phone'=>$userPhone,'code'=>$code,'create_time'=>$time,'type'=>'1','from'=>'aliyun']);
        return response($this->formatDataBody($result));
      } catch (\Exception $e) {
        return response($this->formatDataBody($e,201,'发送失败，请重试'));
      }
    }
    /**
     * 阿里云通道发送短信
     */
    function sendSms($userPhone,$signName,$templateCode,$code) {

        $params = array ();

        // *** 需用户填写部分 ***

        // fixme 必填: 请参阅 https://ak-console.aliyun.com/ 取得您的AK信息
        $accessKeyId = $this->accessKeyId;
        $accessKeySecret = $this->accessKeySecret;

        // fixme 必填: 短信接收号码
        $params["PhoneNumbers"] = $userPhone;

        // fixme 必填: 短信签名，应严格按"签名名称"填写，请参考: https://dysms.console.aliyun.com/dysms.htm#/develop/sign
        $params["SignName"] = $signName;

        // fixme 必填: 短信模板Code，应严格按"模板CODE"填写, 请参考: https://dysms.console.aliyun.com/dysms.htm#/develop/template
        $params["TemplateCode"] = $templateCode;

        // fixme 可选: 设置模板参数, 假如模板中存在变量需要替换则为必填项
        $params['TemplateParam'] = Array (
            "code" => $code
        );

        // fixme 可选: 设置发送短信流水号
        // $params['OutId'] = "12345";

        // fixme 可选: 上行短信扩展码, 扩展码字段控制在7位或以下，无特殊需求用户请忽略此字段
        // $params['SmsUpExtendCode'] = "1234567";


        // *** 需用户填写部分结束, 以下代码若无必要无需更改 ***
        if(!empty($params["TemplateParam"]) && is_array($params["TemplateParam"])) {
            $params["TemplateParam"] = json_encode($params["TemplateParam"], JSON_UNESCAPED_UNICODE);
        }
        // var_dump($params);

        // 初始化SignatureHelper实例用于设置参数，签名以及发送请求
        $helper = new SignatureHelper();

        // 此处可能会抛出异常，注意catch
        $content = $helper->request(
            $accessKeyId,
            $accessKeySecret,
            "dysmsapi.aliyuncs.com",
            array_merge($params, array(
                "RegionId" => "cn-hangzhou",
                "Action" => "SendSms",
                "Version" => "2017-05-25",
            ))
            // fixme 选填: 启用https
            // ,true
        );

        return $content;
    }

    public function getAppVersion(request $request){
      $state=0;
      $DBData=DB::table('app_ver')->orderby('id','desc')->first();
      $ver=$DBData->ver;
      $url=$DBData->url;
      $oldver=$request->ver;
      if($ver>$oldver)$state=1;
      $result=[
        'ver' => $ver,
        'url' => $url,
        'state'=>$state
    ];
      return json_encode($result);
    }
    public function updateAppVersion(request $request){
        // Start transaction!
        DB::beginTransaction();
        try {
          $ver=$request->ver;
          $url=$request->url;
          DB::insert("insert into app_ver (ver,url) values ('$ver','$url')");
          $status=1;
        }
        catch(\Exception $e)
        {
            DB::rollback();
            $status=0;
        }
        DB::commit();
        return json_encode(['status'=>$status]);
    }
    /**
     * 文件上传
     * @param  Request $request [description]
     * @return [type]           [description]
     */
    public function uploadFile(Request $request)
    {
        $file = $request->file('files');
        $fileExtension = $file->getClientOriginalExtension();
        $fileOriginalName = $file->getClientOriginalName();
        list($time1, $time2) = explode(' ', microtime());
        $microTime = (float) $time2 + (float) $time1;
        $newName = $microTime . "." . $fileExtension;
        $ossConfigData = config('oss.' . config('oss.default'));
        if (in_array($fileExtension, $ossConfigData['img_ext'])) {
            $bucketName = $ossConfigData['image_bucket'];
        } else {
            $bucketName = $ossConfigData['file_bucket'];
        }
        //先放到服务器，再上传到OSS
        $localPath = public_path() . '/uploads';
        $file->move($localPath, $newName);

        $ossPath = 'tmpfile/' . $newName;

        $result = OSS::publicUpload($bucketName, $ossPath, $localPath . '/' . $newName);
        $ossUrl = OSS::getPublicUploadUrl($bucketName, $ossPath);

        if ($result) {
            echo json_encode(['name' => $fileOriginalName, 'url' => $ossUrl]);
        } else {
            echo json_encode(['result' => 999, 'msg' => '上传错误']);
        }
    }

    /**
     * 发送短信验证码
     * @param  Request $request [description]
     * @return [type]           [description]
     */
    public function pushCode(Request $request)
    {
        $postData = $this->ajaxSendSms($request);
        $postData['code'] = mt_rand(100000, 999999);
        $code=$postData['code'];
        $postData['ip'] = $request->ip();
        $postData['type'] = 1;
        $result = $this->dbAddSmsCodeLog($postData);
        if ($result['result'] == 0) {
            if (env('DB_CONNECTION') == 'product_mysql') {
                $result2 = $this->pushCodeTrait(parent::CODE_SEND_SMS, $postData);
                $result['code']=$code;
            } else {
                $result2 = true;
                $result['code']=$code;
            }
            $result = $result2 ? $result : ['result' => -1, 'msg' => '短信发送失败，请重试'];
        }
        echo json_encode($result);
    }

    /**
     * 邮箱认证
     * @return [type] [description]
     */
    public function emailAuth()
    {
        $data = ['md5' => $this->_requestData['flag'], 'email' => $this->_requestData['source']];
        $tableData = $this->validateEmailFlag($data);
        if (!$tableData['id']) {
            $viewData = ['seo' => $this->returnSeoInfo('tanwin_index'), 'validate_result' => false];
            return view('web.company.email_auth_result', $viewData);
        }
        $this->validateEmailFlagSuccess($tableData);

        $userInfo = [
            'account_phone' => $tableData['phone'],
            'new_pwd' => mt_rand(10000000, 99999999) . 'abc',
        ];
        $this->userForgetPwdTrait(parent::CODE_UPDATE_USER_PWD, $userInfo);

        $mailInfo = [
            'mail_address' => $tableData['email'],
            'mail_subject' => '碳银网帐号信息' . time(),
            'mail_content' => '您登录碳银网的密码为:' . $userInfo['new_pwd'],
        ];
        $this->pushEmailData(parent::CODE_SEND_EMAIL, $mailInfo);
        $viewData = ['seo' => $this->returnSeoInfo('tanwin_index'), 'validate_result' => true];
        return view('web.company.email_auth_result', $viewData);
    }
}
